const emailInput = document.querySelector('.email');
const usernameInput = document.querySelector('.ipo');
const passwordInput = document.querySelector('.ipt');
const sendemail = document.querySelector('.sendemail');
const testword = document.querySelector('.testword');
const btn = document.getElementById('btn');
testword.style.display = 'none';

const emailRegex = /^[1-9]\d{4,10}@qq\.com$/;
emailInput.addEventListener('input', validateInputs);
usernameInput.addEventListener('input', validateInputs);
passwordInput.addEventListener('input', validateInputs);

function validateInputs() {
    const isEmailValid = emailRegex.test(emailInput.value);
    const isUsernameNotEmpty = usernameInput.value !== '';
    const isPasswordNotEmpty = passwordInput.value !== '';

    if (isEmailValid && isUsernameNotEmpty && isPasswordNotEmpty) {
        emailInput.style.borderColor = '';
        usernameInput.style.borderColor = '';
        passwordInput.style.borderColor = '';
        sendemail.disabled = false;

        sendemail.addEventListener('click', function () {
            testword.style.display = 'block';
            let number = 60;
            let timeID = setInterval(function () {
                sendemail.innerHTML = `${number}秒内有效`;
                number--;
                if (number === 0) {
                    clearInterval(timeID);
                    sendemail.innerHTML = '发送验证码';
                }
            }, 1000);

            testword.addEventListener('input', function () {
                if (testword.value !== '') {
                    btn.disabled = false;
                } else {
                    btn.disabled = true;
                }
            });

            // 使用 AJAX 发送验证码请求
            sendVerificationCodeRequest();
        });
    } else {
        emailInput.style.borderColor = 'red';
        usernameInput.style.borderColor = 'red';
        passwordInput.style.borderColor = 'red';
        btn.disabled = true;
        sendemail.disabled = true;
    }
}

// 使用 jQuery AJAX 发送验证码请求
$(document).ready(function () {
    // 阻止表单默认提交行为
    $('#emailForm').submit(function (e) {
        e.preventDefault();

        // 使用 AJAX 发送验证码请求
        sendVerificationCodeRequest();
    });

    // 使用 jQuery AJAX 发送验证码请求
    function sendVerificationCodeRequest() {
        const toEmail = $('.email').val();

        $.ajax({
            type: 'POST',
            url: 'EmailServlet',
            data: { toEmail: toEmail },
            success: function (response) {
                // 处理成功响应，可以根据需要执行相应的操作
                console.log(response);
            },
            error: function (error) {
                // 处理错误情况，可以根据需要执行相应的操作
                console.error(error);
            }
        });
    }
});